// src/stores/user.ts
import { defineStore } from 'pinia'
import axios from 'axios'
import { ref } from 'vue'

// 定义用户接口
interface User {
  id: number
  username: string
  // 可以根据实际后端返回的数据结构添加其他字段
  [key: string]: any
}

// 创建 axios 实例，配置基础URL
const api = axios.create({
  baseURL: 'http://localhost:8088' // 后端API地址
})

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const isAuthenticated = ref(false)
  const loading = ref(false)
  const error = ref(null)

  // 登录动作
  const login = async (username: string, password: string) => {
    loading.value = true
    error.value = null
    try {
      const response = await api.post('/login', {
        username,
        password
      })

      // 保存用户信息
      user.value = response.data
      isAuthenticated.value = true
      localStorage.setItem('user', JSON.stringify(response.data))

      return true
    } catch (err: any) {
      error.value = err.response?.data?.detail || '登录失败，请检查用户名和密码'
      return false
    } finally {
      loading.value = false
    }
  }

  // 登出动作
  const logout = () => {
    user.value = null
    isAuthenticated.value = false
    localStorage.removeItem('user')
  }

  // 初始化认证状态
  const initAuth = () => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      user.value = JSON.parse(storedUser)
      isAuthenticated.value = true
    }
  }

  return {
    user,
    isAuthenticated,
    loading,
    error,
    login,
    logout,
    initAuth
  }
})
